package com.cloud.common;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 李均华
 * @date 2021/6/3
 * @desc 用户
 */

public class Gen {

    private static final String PACKAGE_NAME = "com.cloud.example";
    private static final String MODULE_NAME = "shop";
    private static final String URL = "jdbc:mysql://127.0.0.1:3306/shop?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowMultiQueries=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";
    private static final String DRIVER_CLASS_NAME = "com.mysql.cj.jdbc.Driver";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private static final String TABLE_PREFIX = "";

    public static void main(String[] args) {

        generate();
    }

    /**
     * 生成源代码
     */
    protected static void generate() {

        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        mpg.setGlobalConfig(setGlobalConfig());

        // 数据源配置
        mpg.setDataSource(setDataSourceConfig());

        // 包配置
        mpg.setPackageInfo(setPackageConfig());

        // 自定义配置
//        mpg.setCfg();

        // 模板配置
//        mpg.setTemplate(setTemplateConfig());

        // 策略配置
        mpg.setStrategy(setStrategyConfig());
        mpg.execute();
    }

    /**
     * 设置全局配置
     * @return  全局配置
     */
    public static GlobalConfig setGlobalConfig() {
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("com.cloud.example.user.dir") + "/src/main/java";
        gc.setOutputDir(projectPath);
        gc.setAuthor("李均华");
        gc.setOpen(false);
        gc.setActiveRecord(true);
        gc.setFileOverride(true);
        gc.setIdType(IdType.AUTO);
        gc.setServiceName("%sService");
        gc.setMapperName("%sDao");
        gc.setBaseColumnList(true);
        return gc;
    }

    /**
     * 设置数据源配置
     * @return  数据源配置
     */
    public static DataSourceConfig setDataSourceConfig() {
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl(URL);
        dsc.setDriverName(DRIVER_CLASS_NAME);
        dsc.setUsername(USERNAME);
        dsc.setPassword(PASSWORD);
        return dsc;
    }

    /**
     * 设置包配置
     * @return  包配置信息
     */
    public static PackageConfig setPackageConfig() {
        PackageConfig pc = new PackageConfig();
        pc.setParent(PACKAGE_NAME);
        pc.setModuleName(MODULE_NAME);
        pc.setController("controller");
        pc.setEntity("entity");
        pc.setMapper("dao");
        pc.setService("service");
        pc.setServiceImpl("service.impl");
        pc.setXml("mapper");
        return pc;
    }

    /**
     * 设置模板
     * @return  模板配置信息
     */
    public static TemplateConfig setTemplateConfig() {
        TemplateConfig tc = new TemplateConfig();
        tc.setController("/templates/java/controller.java.vm");
        tc.setService("/templates/java/service.java.vm");
        tc.setServiceImpl("/templates/java/serviceImpl.java.vm");
        tc.setEntity("/templates/java/entity.java.vm");
        tc.setMapper("/templates/java/mapper.java.vm");
        tc.setXml("/templates/java/mapper.xml.vm");
        return tc;
    }

    /**
     * 自定义配置，设置页面与sql模板
     * @param config
     * @return
     */
//    public static InjectionConfig setInjectionConfig(Configuration config) {
//        String projectPath = config.getString("output.dir");
//        if(StringUtils.isBlank(projectPath)) {
//            projectPath = System.getProperty("com.cloud.example.user.dir");
//        }
//
//        InjectionConfig cfg = new InjectionConfig() {
//            @Override
//            public void initMap() {
//            }
//        };
//        List<FileOutConfig> focList = new ArrayList<>();
//        final String basePath = projectPath;
//        //  自定义 index.vue生成
//        focList.add(new FileOutConfig("/templates/vue/index.vue.vm") {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输入文件名称
//                return basePath + File.separator + "ui"  + File.separator + StringUtils.uncapitalize(tableInfo.getEntityName()) + File.separator + "index.vue";
//            }
//        });
//        //  自定义 add-or-update.vue生成
//        focList.add(new FileOutConfig("/templates/vue/add-or-update.vue.vm") {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输入文件名称
//                return basePath + File.separator + "ui" + File.separator + StringUtils.uncapitalize(tableInfo.getEntityName()) + File.separator + "add-or-update.vue";
//            }
//        });
//        //  自定义 menu.sql生成
//        focList.add(new FileOutConfig("/templates/sql/menu.sql.vm") {
//            @Override
//            public String outputFile(TableInfo tableInfo) {
//                // 自定义输入文件名称
//                return basePath + File.separator + "sql" + File.separator + StringUtils.uncapitalize(tableInfo.getEntityName()) + File.separator + "menu.sql";
//            }
//        });
//        cfg.setFileOutConfigList(focList);
//        return cfg;
//    }

    /**
     * 设置策略
     * @return
     */
    public static StrategyConfig setStrategyConfig() {
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setControllerMappingHyphenStyle(true);
        if(StringUtils.isNotBlank(TABLE_PREFIX)) {
            strategy.setTablePrefix(TABLE_PREFIX.split(",", -1));
        }
        strategy.setLogicDeleteFieldName("deleted");
        List<TableFill> fills = new ArrayList<>();
        String[] insertFields = new String[2];
        insertFields[0] = "create_id";
        insertFields[1] = "create_time";
        fills.addAll(Arrays.stream(insertFields).distinct().map(field -> new TableFill(field, FieldFill.INSERT)).collect(Collectors.toList()));
        String[] updateFields = new String[2];
        updateFields[0] = "update_id";
        updateFields[1] = "update_time";
        fills.addAll(Arrays.stream(updateFields).distinct().map(field -> new TableFill(field, FieldFill.UPDATE)).collect(Collectors.toList()));
        if (fills.size() > 0) {
            strategy.setTableFillList(fills);
        }
        return strategy;
    }
}
